﻿<template>
  <div v-if = 'showTinymce'>
    <editor v-model = "currentValue" :init = "getInitConfig" id = 'tintmceContent' :disabled = 'disabled'></editor>
    <remote-js src = 'static/Tinymce/js/html-docx.js'></remote-js>
  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver'
import axios from 'axios'
// 编辑器插件plugins
// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import 'tinymce/plugins/image'// 插入上传图片插件
import 'tinymce/plugins/table'// 插入表格插件
import 'tinymce/plugins/lists'// 列表插件
import 'tinymce/plugins/wordcount'// 字数统计插件
import 'tinymce/plugins/link' // 超链接
import 'tinymce/plugins/colorpicker' // 选择颜色
import 'tinymce/plugins/textcolor' // 文本颜色
// import 'tinymce/plugins/paste'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/print'
import 'tinymce/plugins/toc'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/pagebreak' // 分页符,用于使用CMS系统时将内容拆分为数个页面
/* global htmlDocx */
export default {
  components: {
    Editor,
    // 定义一个组件,在本组件中使用,用于引入js文件
    'remote-js': {
      render (createElement) {
        return createElement('script', {attrs: {type: 'text/javascript', src: this.src}})
      },
      props: {
        src: { type: String, required: true }
      }
    }
  },
  props: {
    // 配置
    initConfig: {
      type: Object,
      default: function () {
        return {}
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // 默认值
    defaultValue: {
      type: String
    },
    // 初始化的状态
    showTinymce: {
      type: Boolean
    }
  },
  computed: {
    getInitConfig () {
      return Object.assign(this.initConfigDefault, this.initConfig)
    }
  },
  data () {
    return {
      currentValue: this.defaultValue || null,
      initConfigDefault: {
        height: window.screen.height > 800 ? 660 : 400, // 根据浏览器的高度来设置编辑器的高度
        language_url: 'static/Tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: 'static/Tinymce/skins/ui/oxide',
        plugins: 'lists image table wordcount link colorpicker textcolor searchreplace insertdatetime toc print anchor pagebreak',
        image_uploadtab: true, // 可以上传本地图片
        browser_spellcheck: true, // 拼写检查
        branding: false, // 去水印
        elementpath: false, // 禁用编辑器底部的状态栏
        statusbar: false, // 隐藏编辑器底部的状态栏
        paste_data_images: true, // 允许粘贴图像
        powerpaste_word_import: 'propmt', // 参数可以是propmt, merge, clear，效果自行切换对比
        powerpaste_html_import: 'propmt', // propmt, merge, clear
        powerpaste_allow_local_images: true,
        paste_retain_style_properties: 'color font-size line-height background text-align border',
        paste_webkit_styles: 'all', // 在WebKit中粘贴时要保留的样式
        paste_convert_word_fake_lists: false, // 禁用复制word中的列表内容时，转换为html的UL或OL格式
        pagebreak_split_block: true, // 插入时拆分块元素
        automatic_uploads: true, // 自动上传
        image_advtab: true, // 自定上传的样式
        menubar: true, // 隐藏(设置为false)最上方menu
        content_style: 'p{margin-top:0;margin-bottom:0;line-height:1.6em}',
        fontsize_formats: '11px 12px 14px 16px 18px 24px 36px 48px',
        toolbar: 'insertfile undo redo | styleselect | bold italic | fontsizeselect | ' +
          'alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | ' +
          'link image | print toc anchor pagebreak',
        images_upload_handler: function (blobInfo, success, failure) {
          var file = blobInfo.blob()
          var reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onloadend = function () {
            if (file.name && file.size) {
              // 这里执行文件上传的方法
              axios({
                url: $URL.IMG_UPLOAD_URL + '/fileset/upload',
                method: 'post',
                data: {
                  file_name: file.name,
                  file_length: file.size,
                  file_content: reader.result.split(',')[1]
                }
              }).then(data => {
                let dataResult = data.data.result
                if (dataResult.code === 'success') {
                  let url = dataResult.link_url.replace('/dl/', '/')
                  success(url)
                } else {
                  failure('上传图片失败')
                }
              }).catch(() => {
                failure('上传图片出错')
              })
            }
          }
        }
      }
    }
  },
  mounted () {
    tinymce.init({})
  },
  watch: {
    currentValue: {
      deep: true,
      handler (val) {
        this.$emit('update:defaultValue', val)
      }
    },
    showTinymce: {
      deep: true,
      handler (val) {
        if (val) {
          this.initMethod()
        }
      }
    }
  },
  methods: {
    // 初始化的方法
    initMethod () {
      this.$nextTick(() => {
        this.currentValue = this.defaultValue ? this.defaultValue : ''
      })
    },
    // 导出成word的方法
    exportWordMethod () {
      var contentDocument = tinymce.get('tintmceContent').getDoc()
      var regularImages = contentDocument.querySelectorAll('img')
      if (regularImages.length) {
        for (let i = 0; i < regularImages.length; i++) {
          this.getPicInfo(regularImages[i], i + 1, regularImages.length)
        }
      } else {
        var content = '<!DOCTYPE html>' + contentDocument.documentElement.outerHTML
        var converted = htmlDocx.asBlob(content, {orientation: 'portrait'})
        saveAs(converted, 'feijia_icp.docx')
      }
    },
    drawPic (imgElement, index, totalCount, type) {
      var canvas = document.createElement('canvas')
      var ctx = canvas.getContext('2d')
      imgElement.setAttribute('crossOrigin', 'anonymous')
      // preparing canvas for drawing
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      canvas.width = imgElement.width
      canvas.height = imgElement.height
      ctx.drawImage(imgElement, 0, 0)
      // by default toDataURL() produces png image, but you can also export to jpeg
      // checkout function's documentation for more details
      var dataURL = canvas.toDataURL(type)
      imgElement.setAttribute('src', dataURL)
      canvas.remove()
      if (index === totalCount) {
        var contentDocument = tinymce.get('tintmceContent').getDoc()
        var content = '<!DOCTYPE html>' + contentDocument.documentElement.outerHTML
        var converted = htmlDocx.asBlob(content, {orientation: 'portrait'})
        saveAs(converted, 'feijia_icp.docx')
      }
    },
    // 获取图片的信息
    getPicInfo (imgElement, index, totalCount) {
      axios({
        url: imgElement.getAttribute('src'),
        method: 'get'
      }).then(data => {
        this.drawPic(imgElement, index, totalCount, data.headers['content-type'])
      })
    }
  }
}
</script>

<style lang="scss">
.tox-tinymce-aux {
  z-index: 999999 !important;
}
.tox-dialog-wrap {
  z-index: 9999999 !important;
}
.tox .tox-dialog__popups {
  z-index: 99999999 !important;
}
</style>
